package com.company.nuwa.common.utils;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页数据封装类
 * Created by macro on 2019/4/19.
 */
public class PageUtil {

    /**
     * 重新转换过的list转成page
     *
     * @param pageInfo
     * @param list
     * @param <T>
     * @return
     */
    public static <T> PageInfo<T> transformPageInfo(PageInfo pageInfo, List<T> list) {
        PageInfo<T> result = new PageInfo<T>();
        result.setTotal(pageInfo.getPages());
        result.setPageNum(pageInfo.getPageNum());
        result.setPageSize(pageInfo.getPageSize());
        result.setTotal(pageInfo.getTotal());
        result.setList(list);
        result.setHasNextPage(pageInfo.isHasNextPage());
        result.setHasPreviousPage(pageInfo.isHasPreviousPage());
        return result;
    }

    /**
     * 分隔列表
     *
     * @param list
     * @param groupSize
     * @param <R>
     * @return
     */
    public static <R> List<List<R>> splitList(List<R> list, int groupSize) {
        int length = list.size();
        int num = (length + groupSize - 1) / groupSize;
        List<List<R>> newList = new ArrayList(num);

        for (int i = 0; i < num; ++i) {
            int fromIndex = i * groupSize;
            int toIndex = (i + 1) * groupSize < length ? (i + 1) * groupSize : length;
            newList.add(list.subList(fromIndex, toIndex));
        }

        return newList;
    }

    /**
     * empty
     *
     * @param <T>
     * @return
     */
    public static <T> PageInfo<T> empty() {
        return PageInfo.of(Lists.newArrayList());
    }

}